
package com.y.fund.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

public class MD5Util{

    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /** Convert byte array to hexadecimal string */
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }
        return resultSb.toString();
    }

    /** Convert byte to hexadecimal */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

	public static String encode(String plaintext){
        return encode(plaintext, null);
    }
    
    public static String encode(String plaintext, String charset){
    	if(null == plaintext) {
    		return null;
    	}
        try {
        	return encode(plaintext.getBytes(null==charset? StrUtil.CHARSET_UTF8 : charset));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        return null;
    }
    
    public static String encode(byte[] plaintext){
    	if(null == plaintext) {
    		return null;
    	}
    	 String resultString = null;
         try {
             MessageDigest md = MessageDigest.getInstance("MD5");
             resultString = byteArrayToHexString(md.digest(plaintext));
         } catch (Exception e) {
             e.printStackTrace();
         }
         return resultString;
    }

    public static String getMD5SubStr(String inStr, int length) {
		return encode(inStr).substring(0, length);
    }
    
}
